import 'dart:async';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

import '../../utils/logger.dart';
import '../test/index.dart' as test;
import '../../widgets/tags/menu_item.dart';
import '../../widgets/block_widget.dart';
import '../../widgets/grid_wrap.dart';
import '../../tbicons.dart';
import '../../models/member_model.dart';
import '../../utils/tools.dart';
import '../../widgets/flexible_space_bar_noscale.dart';

import '../../application.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with AutomaticKeepAliveClientMixin<IndexPage> {
  MemberModel? _member;
  bool _isLogin = false;
  StreamSubscription<LoginStateEvent>? loginSubscribe;
  late ScrollController _controller;
  double _sPercent = 0;
  double avatarSize = 64;
  double paddingBottom = 30;

  @override
  initState() {
    super.initState();
    logger.info('member init');
    _controller = ScrollController();
    _controller.addListener(_onScroll);
    loginSubscribe = app.on<LoginStateEvent>().listen(onLoginState);
    checkLogin();
  }

  @override
  dispose() {
    loginSubscribe?.cancel();
    super.dispose();
  }

  _onScroll() {
    final position = _controller.position as ScrollPositionWithSingleContext;
    //logger.info(position.pixels);
    double newPercent = 1 - math.min(1, position.pixels / 120);
    if (_sPercent != newPercent) {
      setState(() {
        _sPercent = newPercent;
        avatarSize = 24 + (40 * _sPercent);
        paddingBottom = 12 + (18 * _sPercent);
      });
    }
  }

  checkLogin() async {
    if (!app.isLogin) {
      await Future.delayed(const Duration(milliseconds: 500));
      MyDialog.confirm('现在登录？').then((value) {
        if (value ?? false) {
          app.route('/login');
          MyDialog.toast('请登录');
        }
      });
    } else {
      initProfile();
    }
  }

  onLoginState(event) {
    if (event.data ?? false) {
      initProfile();
    } else {
      setState(() {
        _isLogin = false;
        _member = null;
      });
    }
  }

  Future<void> initProfile([bool force = false]) async {
    _member = await app.getProfile(force: force);
    setState(() {
      _isLogin = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final colorScheme = Theme.of(context).colorScheme;
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: () {
          return initProfile(true);
        },
        child: CustomScrollView(
          controller: _controller,
          physics: const AlwaysScrollableScrollPhysics()
            ..applyTo(const BouncingScrollPhysics()),
          slivers: [
            SliverAppBar(
              actions: [
                IconButton(
                  onPressed: () {
                    app.route('/setting');
                  },
                  icon: const Icon(Icons.settings),
                ),
              ],
              elevation: 0,
              expandedHeight: 140,
              pinned: true,
              flexibleSpace: FlexibleSpaceBarNoScale(
                centerTitle: false,
                titlePadding: EdgeInsets.only(left: 20, bottom: paddingBottom),
                collapseMode: CollapseMode.pin,
                title: Row(
                  children: [
                    (_member?.avatar.isEmpty ?? true)
                        ? Icon(
                            Icons.person,
                            color: colorScheme.onPrimary,
                            size: avatarSize,
                          )
                        : Tools.image(
                            _member!.avatar,
                            width: avatarSize,
                            height: avatarSize,
                          ),
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        GestureDetector(
                          onTap: () {
                            if (!_isLogin) {
                              app.route('/login');
                            }
                          },
                          child: Text(
                            _member?.nickname ?? '未登录',
                            style: const TextStyle(fontSize: 18),
                          ),
                        ),
                        if (_isLogin && avatarSize >= 40)
                          MobileBind(
                            mobile: _member?.mobile,
                            bind: _member?.mobileBind,
                          ),
                      ],
                    ),
                  ],
                ),
                background: Container(
                  color: colorScheme.primary,
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: const Alignment(0, 1),
                    end: const Alignment(0, -1),
                    colors: <Color>[
                      colorScheme.primary.withAlpha(0),
                      colorScheme.primary,
                    ],
                  ),
                ),
                padding: const EdgeInsets.only(left: 20, right: 20, top: 10),
                child: Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: colorScheme.surface,
                    borderRadius: const BorderRadius.all(Radius.circular(5)),
                  ),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Expanded(
                        child: Column(
                          children: [
                            Text('0.0'),
                            Text('公告'),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                        child: VerticalDivider(
                          width: 1,
                          thickness: 0.5,
                          color: Colors.black26,
                        ),
                      ),
                      Expanded(
                        child: Column(
                          children: [
                            Text('0.0'),
                            Text('评论'),
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20,
                        child: VerticalDivider(
                          width: 1,
                          thickness: 0.5,
                          color: Colors.black26,
                        ),
                      ),
                      Expanded(
                        child: Column(
                          children: [
                            Text('0'),
                            Text('收藏'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: BlockWidget(
                margin: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: colorScheme.surface,
                  borderRadius: const BorderRadius.all(Radius.circular(5)),
                ),
                title: const BlockTitle(
                  title: Text('常用工具'),
                ),
                child: GridWrap(
                  crossAxisCount: 4,
                  children: [
                    TagMenuItem(
                      icon: const Icon(Tbicons.location_light),
                      text: '地址',
                      onTap: () {
                        app.route('/member/addresses');
                      },
                    ),
                    TagMenuItem(
                      icon: const Icon(Tbicons.round_ticket),
                      text: '优惠券',
                      onTap: () {
                        app.route('/member/coupons');
                      },
                    ),
                    TagMenuItem(
                      icon: const Icon(Tbicons.question),
                      text: '帮助',
                      onTap: () {
                        app.route('/help');
                      },
                    ),
                    TagMenuItem(
                      icon: const Icon(Tbicons.info),
                      text: '关于',
                      onTap: () {
                        app.route('/about');
                      },
                    ),
                    TagMenuItem(
                      icon: const Icon(Tbicons.comment),
                      text: '我的留言',
                      onTap: () {
                        app.route('/member/feedback');
                      },
                    ),
                  ],
                ),
              ),
            ),
            const SliverToBoxAdapter(
              child: test.IndexPage(),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class MobileBind extends StatelessWidget {
  final String? mobile;
  final bool? bind;

  const MobileBind({Key? key, this.mobile, this.bind}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          mobile ?? '未绑定',
          style: TextStyle(
            color: mobile == null ? Colors.black26 : Colors.white,
            fontSize: 14,
          ),
        ),
        const SizedBox(width: 10),
        if (bind != null)
          Text(
            bind! ? '已绑定' : '未绑定',
            style: TextStyle(
              color: bind! ? Colors.white : Colors.black26,
              fontSize: 12,
            ),
          ),
      ],
    );
  }
}
